package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.cucc.common.util.DateUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.base.staticdata.ServiceOfferConst;
import com.ztesoft.bss.base.util.LocalAttrUtils;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.zsmart.core.util.DateUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 精品网全程要求完成时间
 **/
@Service
public class AZJPWAllCompleteTimeHandler extends AbstractAttrHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;
    @Autowired
    private IOperateSceneInstService operateSceneInstService;
    @Override
    public void init(CommonAttrVO commonAttr) {
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        KiteAttr attr =querySceneInstService.getCommonAttr(sceneInstId, commonAttr.getFieldName());
        KiteProdInst prodInst = querySceneInstService.listProdInstsFromOfferInst(KiteWebContext.getContext().getCustId(), kiteSceneInst.getRootInstId()).stream()
            .filter(inst -> !KiteStringUtils.equalsAny(inst.getActionType().name(), ActionType.X.name(), ActionType.D.name()))
            .findFirst().orElse(null);
        String serviceOfferId = Optional.ofNullable(kiteSceneInst).map(KiteSceneInst::getServiceOfferId).orElse("");
        String nodeCode = StringUtils.EMPTY;
        Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();
        if (Objects.nonNull(extParams)&& extParams.containsKey("nodeCode")) {
            nodeCode = KiteMapUtils.getString(extParams,"nodeCode");
        }else {
            nodeCode = querySceneInstService.getExtParameterValue(sceneInstId, "nodeCode");
        }
        if (KiteStringUtils.equalsAny(serviceOfferId, ServiceOfferConsts.SERVICE_OFFER_ORDER, "1024", ServiceOfferConsts.SERVICE_OFFER_MODIFY)) {
            if (KiteStringUtils.isEmpty(commonAttr.getValue())) {
                LocalDateTime nowDate = LocalDateTime.now();
                // 追加天数
                String value = nowDate.plusDays(5).format(DateTimeFormatter.ofPattern(DateFormatUtils.DATE_MINUTE_FORMAT));
                commonAttr.setValueDesc(value);
                setCommonAttr(commonAttr);
            }
        }else if(KiteStringUtils.equalsAny(serviceOfferId,LocalServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK)){
            if (KiteStringUtils.isEmpty(commonAttr.getValue())) {
                String value=StringUtils.EMPTY;
                //核查重提
                if ("OrderResubmit".equals(nodeCode)) {
                    value  = LocalAttrUtils.compareDate(commonAttr, prodInst.getProdId(),null);
                    attr.setDefaultValue(value);
                } else {
                    value = LocalAttrUtils.getInstance().wholeOffsetDay(prodInst.getProdId(), null);
                    attr.setDefaultValue(value);
                }
                commonAttr.setValue(value);
                commonAttr.setValueDesc(value);
                setCommonAttr(commonAttr);
            }
        }
    }

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        KiteInst kiteInst = querySceneInstService.getKiteInst(sceneInst.getCustId(), sceneInst.getRootInstType(), sceneInst.getRootInstId());
        List<DcPublic> dclist = DcPublicCache.get("20210719001");
        // 是否五大双线落地方产品，全程要求完成时间一直必填
        boolean flag = (dclist != null) && dclist.stream().anyMatch(dcPublic -> KiteStringUtils.isEqual(kiteInst.getSpecId(), dcPublic.getCodeb()));
        if (!flag) {
            //获取页面勾选的操作类型
            List<String> serviceOfferIdList = querySceneInstService.getExtParameterValue(sceneInstId, "BUSI_CHANGE_SERVICEOFFERID");
            IOperateSceneCommonService operateSceneCommonService = SpringUtil.getBean(IOperateSceneCommonService.class);
            KiteAttr kiteAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.WHOLE_PROCESS_TIME);
            if (Objects.nonNull(kiteAttr)) {
                if (!KiteListUtils.isEmpty(serviceOfferIdList) && serviceOfferIdList.size() == 1) {
                    if (serviceOfferIdList.contains("1009") || serviceOfferIdList.contains("1080")) {
                        kiteAttr.setIsNull("T");
                    } else {
                        kiteAttr.setIsNull("F");
                    }
                } else {
                    kiteAttr.setIsNull("F");
                }
                operateSceneCommonService.setCommonAttr(sceneInstId, kiteAttr);
            }
        }

        // 是否为页面初始化渲染，是（T），跳过校验
        String isInitPageRenderFlag = querySceneInstService.getExtParameterValue(sceneInstId, "isInitPageRenderFlag");
        if (KiteStringUtils.isEqual(isInitPageRenderFlag, LocalKeyConsts.IFTRUE_T)) {
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        if (KiteStringUtils.isEmpty(value)) {
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        //重提初始化不校验
        //fixme 可能导致频繁访问缓存,上线临时处理方案
        Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();
        if (Objects.nonNull(extParams) && extParams.containsKey("nodeCode")) {
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        String nodeCode = querySceneInstService.getExtParameterValue(sceneInstId, "nodeCode");
        if(null==nodeCode){
            nodeCode= MapUtils.getString(extParams,nodeCode);
        }
        String allCompleteTimePattern = "yyyy-MM-dd HH:mm:ss";
        String azCompleteTimePattern = "yyyy-MM-dd HH:mm:ss";
        Date curDate = getCurrentDate();
        Date allCompleteTime = null;
        if (KiteStringUtils.isNotEmpty(value)) {
            if (allCompleteTimePattern.length() > value.length()) {
                allCompleteTimePattern = allCompleteTimePattern.substring(0, value.length());
            }
            try {
                allCompleteTime = DateUtils.parseStrToDate(value, allCompleteTimePattern);
            } catch (Exception e) {
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
            }
            //全程要求完成时间不能早于当前时间
            if (DateUtil.compare(curDate, allCompleteTime) > 1){
                BssException.throwOut("", "",  "要求完成时间不能早于当前时间");
            }

            String scenInstId = KiteWebContext.getContext().getCurrentSceneInstId();
            List<KiteProdInst> prodInstList = querySceneInstService.listProdInsts(scenInstId);
            //A端要求完成时间
            String aCompleteTimeStr = querySceneInstService.getCommonAttrValue(sceneInstId, "2_0000122");
            //Z端要求完成时间
            String zCompleteTimeStr = querySceneInstService.getCommonAttrValue(sceneInstId, "2_0000123");
            List<String> list = new ArrayList<>();
            list.add(aCompleteTimeStr);
            list.add(zCompleteTimeStr);
            for (String complteTimeStr : list) {
                if (KiteStringUtils.isNotEmpty(complteTimeStr)) {
                    if (azCompleteTimePattern.length() > complteTimeStr.length()) {
                        azCompleteTimePattern = azCompleteTimePattern.substring(0, complteTimeStr.length());
                    }

                    Date completeDate = null;
                    try {
                        completeDate = DateUtils.parseStrToDate(complteTimeStr, azCompleteTimePattern);
                    } catch (Exception e) {
                        ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
                    }

                    //AZ端完成时间需要小于全局完成当前时间
                    if (null != completeDate && DateUtil.compare(completeDate, allCompleteTime) > 1) {

                        // 是否为页面初始化渲染，是（T），跳过校验
                        if (KiteStringUtils.isEqual(isInitPageRenderFlag, LocalKeyConsts.IFTRUE_T)) {
                            return super.apply(sceneInstId, fieldName, value, value);
                        }
                        if (KiteStringUtils.equalsAny(nodeCode, "OrderSigned")) {
                            // 签订环节不做校验
                            return super.apply(sceneInstId, fieldName, value, value);
                        } else {
                            BssException.throwOut(KeyConsts.LOG_MODULE, "", "A、Z端要求完成时间不能晚于全程要求完成时间");
                        }
                    }
                }
            }

        }
        //资源核查跨域优化
        defaultCheck(sceneInstId,fieldName,value);

        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }
    public void defaultCheck(String sceneInstId ,String fieldName,String value){
        // 是否为页面初始化渲染，是（T），跳过校验

        String isInitPageRenderFlag = querySceneInstService.getExtParameterValue(sceneInstId, "isInitPageRenderFlag");
        if(null!=isInitPageRenderFlag&&KiteStringUtils.isEqual(isInitPageRenderFlag, LocalKeyConsts.IFTRUE_T)) {
            KiteAttr finishTime = querySceneInstService.getCommonAttrsByFieldName(sceneInstId, fieldName, "204");
            if(finishTime!=null&&KiteStringUtils.isNotEmpty(finishTime.getDefaultValue())&&DateFormatUtils.compareDate(value,finishTime.getDefaultValue() , DateFormatUtils.DATE_MINUTE_FORMAT) < 0){
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("可选择的日期不能早于初始化的日期:"+finishTime.getDefaultValue());
            }
        }
    }
    public Date getCurrentDate() {
        Date toDay = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String toDayStr = sdf.format(toDay);
        Date newDate = null;
        try {
            newDate = sdf.parse(toDayStr);

        } catch (Exception e) {
            return newDate;
        }
        return newDate;
    }
    public void checkTime(String type, KiteAttr ...attr) {
        if (Objects.isNull(attr)) {
            return;
        }
        List<KiteAttr> kiteAttrList = Arrays.asList(attr);
        if (KiteListUtils.isNotEmpty(kiteAttrList)) {
            kiteAttrList.forEach(kiteAttr -> {
                String currDate = kiteAttr.getValue();
                String originDate = kiteAttr.getOriginValue();
                // 如果加急，不能晚于之前的完成时间
                if ("URGENT".equals(type) && KiteStringUtils.isNotEmpty(originDate)) {
                    if (DateFormatUtils.compareDate(currDate, originDate, LocalKeyConsts.DATE_FORMAT) > 0) {
                        BssException.throwOut(KeyConsts.LOG_MODULE, "","加急，要求完成时间不能晚于之前的完成时间");
                    }
                }
                // 如果是延期，不能早于之前的完成时间
                if ("POSTPONE".equals(type) && KiteStringUtils.isNotEmpty(originDate)) {
                    if (DateFormatUtils.compareDate(currDate, originDate, LocalKeyConsts.DATE_FORMAT) < 0) {
                        BssException.throwOut(KeyConsts.LOG_MODULE, "","延期，要求完成时间不能早于之前的完成时间");
                    }
                }
                // 校验全程要求完成时间大于当前时间
                if ("ORD10012".equals(kiteAttr.getFieldName()) && (DateFormatUtils.compareDate(currDate, DateFormatUtils.getFormatedDate(), LocalKeyConsts.DATE_FORMAT) < 0)) {
                    BssException.throwOut(KeyConsts.LOG_MODULE, "","全程要求完成时间不能小于当前时间");
                }
            });
        }
    }

    /**
     * 跨域优化资源核查使用
     * @param commonAttr
     * @param prodInst
     * @return
     */
    public String compareDate(CommonAttrVO commonAttr,KiteProdInst prodInst){
        String nowFinishTime = LocalAttrUtils.getInstance().wholeOffsetDay(prodInst.getProdId(), null);
        String origin = commonAttr.getOriginValue();
        if(null==origin){
            origin=commonAttr.getOldValue();
        }
        if(origin==null){
            return nowFinishTime;
        }
        if(DateFormatUtils.compareDate(origin, nowFinishTime, DateFormatUtils.DATE_MINUTE_FORMAT) < 0){
            return nowFinishTime;
        }else{
            return origin;
        }
    }
    public void specialProd(KiteSceneInst sceneInst,CommonAttrVO commonAttr){
        if(sceneInst.getCartId().equals("2004029")){
            String nodeCode = querySceneInstService.getExtParameterValue(sceneInst.getSceneInstId(), "nodeCode");
            // TODO: 临时处理，二次业务第一次加载清空
            String firstInitLoading = querySceneInstService.getExtParameterValue(sceneInst.getSceneInstId(), "FirstInitLoading");
            if(ServiceOfferConst.service_offer_2826.equals(sceneInst.getServiceOfferId()) && KiteStringUtils.isEmpty(nodeCode) && KiteStringUtils.isEmpty(firstInitLoading)) {
                commonAttr.setValue(null);
                commonAttr.setValueDesc(null);
                setCommonAttr(commonAttr);
                operateSceneInstService.putExtParameter(sceneInst.getSceneInstId(), "FirstInitLoading", "T");
            }
        }

    }
}
